import {ChangeDetectorRef, Component, ViewChild} from '@angular/core';

import {
    AlertController, Events, IonicPage, NavController, NavParams, Platform, Select,
    ToastController
} from 'ionic-angular';
import {CallNumber} from '@ionic-native/call-number';

import "rxjs/add/observable/of";
import *as moment from 'moment';
import {AdpActionSheetController} from'../../../components/common/adp-action-sheet/adp-action-sheet-controller';

import {
    BeClient,
    Marry,
    Child,
    InType,
    EmptyPhone,
    EmptyAddress,
    BeLead,
    BaseInfo
} from '../../../model/pages/client/client-detail/client-detail-main.model';
import {ClientDetailProvider} from '../../../providers/client/client-detail/client-detail.provider'
import {ScheduleStrResourceCh} from "../../../model/pages/schedule/schedule-add/schedule-add.model";
import {ClientNoteEditProvider} from "../../../providers/client/client-note/client-note-edit/client-note-edit.provider";
import {MessageBushService} from "../../../services/common/message-bush.service";
import {FavoriteListProvider} from "../../../providers/client/favorite-list/favorite-list.provider";
import {ProgressSearch} from "../../../model/pages/client/client-note/client-note-list/client-note-list.model";
import {ClientNoteListProvider} from '../../../providers/client/client-note/client-note-list/client-note-list.provider';
import {CallNumberService} from "../../../services/native/call-number/call-number.service";
import {ClientMapProvider} from "../../../providers/client/client-map/client-map.provider";
import {LoadingService} from '../../../services/common/loading.service';
import {ToastService} from '../../../services/common/toast.service';


@IonicPage()
@Component({
    selector: 'page-client-detail',
    templateUrl: 'client-detail.html',
    providers: [
        CallNumber,
        ClientDetailProvider,
        ClientNoteEditProvider,
        FavoriteListProvider,
        ClientNoteListProvider,
        CallNumberService,
        ClientMapProvider,
        LoadingService,
        ToastService,
        AdpActionSheetController
    ]
})
export class ClientDetailPage {
    @ViewChild('selectMobile') selectMobile: Select;
    // 客户其他信息是否展开
    private otherInfoOpenStatus: boolean = false;
    // 客户详情信息收起展开
    private openMsgStatus: boolean = false;
    // 标记是否收藏
    private collectStatus: boolean = false;
    // 中心信息切换
    private messageType: number;
    // 当前客户id
    private clientId: number;
    // 客户头像
    private clientAvatar: string;
    // 是否进入页面状态
    private inPageStatus: boolean;
    // 用于全局控制弹窗的对象
    private alertObj;
    // 页面提示
    private curStrResource = ScheduleStrResourceCh;
    // 当前clientNum
    private currentClientNum: any;
    // 客户等级class
    private levelClass: string = '';
    // 准客户
    private clientLData: BeLead = new BeLead();
    // 婚育模型
    private marry = Marry;
    // 子女模型
    private child = Child;
    // 购买类型
    private inType = InType;
    // 空的电话列表
    private emptyPhone = EmptyPhone;
    // 空的地址列表
    private emptyAddress = EmptyAddress;
    // 电话状态
    private phoneStatus: boolean = false;
    //是否在收藏夹中
    private isFavorited: boolean = false;
    //初始收藏状态
    private oldFavorited: boolean = false;
    // 客户跟进请求对象
    private getProgress: ProgressSearch = new ProgressSearch();
    // 客户跟进数据
    progressList: any[] = [];

    isMobileWeb;
    isIonViewDidLoad = false;
    // 进入页面状态
    private intoPage:boolean;
    // 请求状态
    private requestStatus:boolean;
    // 数据有效
    private isNull:boolean;
    // 跟进请求
    private progressRequest:boolean;

    constructor(public navCtrl: NavController,
                public navParams: NavParams,
                public platform: Platform,
                public alertCtrl: AlertController,
                public toastCtrl: ToastController,
                public callNumber: CallNumber,
                public ref: ChangeDetectorRef,
                public clientDetailProvider: ClientDetailProvider,
                public favoriteListProvider: FavoriteListProvider,
                public clientNoteEditProvider: ClientNoteEditProvider,
                public clientNoteListProvider: ClientNoteListProvider,
                public callNumberService: CallNumberService,
                public  map: ClientMapProvider,
                public loadingService:LoadingService,
                public toastService:ToastService,
                public adpActionSheetController:AdpActionSheetController,
                private events: Events
                ) {
        this.isMobileWeb = this.platform.is('mobileweb');
    }

    public backButtonHandle = () => this.backToProPage();

    ionViewDidLoad() {
        // 请求前初始化
        this.initClientData();
        // 填充
        this.currentClientNum = this.navParams.get('clientNum');
        this.messageType = 1;
       // this.getLeadsClientData(this.currentClientNum);
        this.isIonViewDidLoad = true;
    }

    ionViewDidEnter() {
        this.inPageStatus = true;
        /*let flag = MessageBushService.getMessage(MessageBushService.keys.clientDetailDataUpdated);
        if (flag == "1" && !this.isIonViewDidLoad) {
            MessageBushService.setMessage(MessageBushService.keys.clientDetailDataUpdated, "0");
            this.getLeadsClientData(this.currentClientNum);
        }*/
        this.getLeadsClientData(this.currentClientNum);
        this.isIonViewDidLoad = false;
        this.intoPage=true;
    }

    ionViewWillLeave() {
        this.inPageStatus = false;
    }

    /**
     * 切换其他信息展开状态
     */
    changeOtherInfoOpenStatus() {
        this.otherInfoOpenStatus = !this.otherInfoOpenStatus;
        this.ref.detectChanges();
    }

    // 请求前初始化数据
    initClientData() {
        this.clientLData.addressList = [{
            address: '',
            defaultIndicator: 0,
            id: '',
            locationLatitude: '',
            locationLongitude: '',
        }];
        this.clientLData.age = '';
        this.clientLData.birthDate = '';
        this.clientLData.carOwnership = 0;
        this.clientLData.childNum = 0;
        this.clientLData.defaultAddress = '';
        this.clientLData.defaultMobile = '';
        this.clientLData.houseOwnership = 0;
        this.clientLData.income = 0;
        this.clientLData.insType = 0;
        this.clientLData.leadId = '';
        this.clientLData.marriageType = 0;
        this.clientLData.mobileList = [{
            defaultIndicator: 0,
            id: '',
            mobile: ''
        }];
        this.clientLData.name = '';
        this.clientLData.occupation = '';
        this.clientLData.otherIns = 0;
        this.clientLData.partyId = '';
        this.clientLData.postcode = '';
        this.clientLData.remark = '';
        this.clientLData.sex = '';
        this.clientLData.source = '';
    }

    // 切换信息类型
    transMessage(num) {
        this.messageType = num;
    }

    // 获取准客户详情
    getLeadsClientData(clientNum) {
        this.loadingService.showLoading();
        this.clientDetailProvider.getClientDetailData(clientNum).subscribe((res) => {
            this.loadingService.dismissLoading();
            this.requestStatus=true;
            if (res && res.leadId) {
                this.clientLData = res;
                this.isNull=true;
                this.getLeadsList(res.tagList);
                // 跟进
                this.getProgress.clientId = this.currentClientNum;
                this.getProgress.clientName = this.clientLData.name;
                if(res.mobileList && res.mobileList.length){
                    let mobile = [];
                    for(let i=0;i<res.mobileList.length;i++){
                        if(res.mobileList[i].mobile){
                            mobile.push(res.mobileList[i].mobile)
                        }
                    }
                    this.getProgress.clientPhone = mobile;
                }


                // this.getProgress.clientType = 2;
                this.getProgress.clientType = 1;
                this.getProgress.limit = 3;
                this.getProgressList(1);
                // 电话
                if (this.clientLData.mobileList.length > 0 && this.clientLData.mobileList[0].mobile) {
                    this.phoneStatus = true;
                  //  this.getProgress.clientPhone = this.clientLData.mobileList[0].mobile;
                } else {
                    this.phoneStatus = false;
                }
                //地址
                if(res.addressList.length){
                    for(let i=0;i<res.addressList.length;i++){
                        res.addressList[i].address = res.addressList[i].address.toUpperCase();
                        if(res.addressList[i].defaultIndicator == 1){
                            this.map.updatePoiByClientId(res.addressList[i].address,res.leadId,1).subscribe(res=>{});
                        }
                    }
                }
                this.clientAvatar = ClientDetailProvider.getClientAvatar(this.clientLData);
            } else {
                this.toastService.showToast('请求数据为空');
            }
            // 收藏
            this.isFavorited = this.clientLData.favorite;
            this.oldFavorited = this.clientLData.favorite;
        }, err => {
            this.loadingService.dismissLoading();
            this.requestStatus=true;
        })
    }

    // 获取跟进
    getProgressList(notLoading) {
        this.clientNoteListProvider.getProgressList(this.getProgress, notLoading).subscribe((res) => {
            this.progressList = res['notes'];
            this.progressRequest=true;
        },err=>{
            this.progressRequest=true;
        })
    }

    /**
     * 跳转到人工线索
     */
    goToleadsList(a) {
        // if(a=="人工线索"){
        if (a == "人工线索") {
            this.intoPage=false;
            this.navCtrl.push("ClientNoteListPage", {"clientNum": this.clientLData.leadId, "tabName": "cule"})
        }
    }

    /**
     * 销售线索展示
     */
    public leadsList = [];

    getLeadsList(list) {
        if (!list || !list.length) return;
        let list2 = ["人工线索"];
        let length = 188 + 50;
        this.leadsList = [];
        for (let i = 0; i < list2.length; i++) {
            length += (list2[i].length * 42 + 32 + 10);
            this.intoPage=false;
            this.leadsList.push(window['unescape'](list2[i].replace(/\\u/g, '%u')));
            if (length >= window.innerWidth) {
                break;
            }
        }
    }

    // 点击收藏
    collectClickHandle() {
        let status = '0';
        if (this.isFavorited) {
            this.favoriteListProvider.removeFromFavorite(this.currentClientNum).subscribe((res) => {
                this.isFavorited = !this.isFavorited;
                this.toastService.showToast('取消收藏成功！');
                if (this.isFavorited == !this.oldFavorited) {
                    status = '1';
                } else {
                    status = '0';
                }
                MessageBushService.setMessage(MessageBushService.keys.favoriteIsUpdated, status);
            });
        } else {
            this.favoriteListProvider.addToFavorites(this.currentClientNum, '1').subscribe((res) => {
                this.isFavorited = !this.isFavorited;
                this.toastService.showToast('收藏成功！');

                if (this.isFavorited == !this.oldFavorited) {
                    status = '1';
                } else {
                    status = '0';
                }
                MessageBushService.setMessage(MessageBushService.keys.favoriteIsUpdated, status);
            });
        }
    }

    // 删除客户
    deleteClient() {
        this.showConfirm('确认删除？',
            () => {
                this.deleteClientRequest();
            },
            () => {
            });
    }

    // 删除客户请求
    deleteClientRequest() {
        this.map.deleteClientLeadsForLBS(this.currentClientNum).subscribe(r=>{
            if(r){
                this.clientDetailProvider.deleteClient(this.currentClientNum).subscribe((res) => {
                    MessageBushService.setMessage(MessageBushService.keys.clientListUpdated, '1');
                    MessageBushService.setMessage(MessageBushService.keys.prospectiveClientsUpdated, '1');

                    this.toastService.showToast('删除客户成功');
                    this.intoPage=false;
                    this.navCtrl.pop();
                }, error2 => {
                    if(error2.status==500){
                        this.toastService.showToast('删除客户失败');
                    }
                });
            }else {
              //  this.toastService.showToast('删除客户失败');
            }
        });
    }


    // 电话列表拨打电话
    /*callPhone(phoneNumber) {
        if (!this.platform.is('cordova')) {
            return false;
        }
        this.callPhoneNumber(phoneNumber);
    }*/

    // 单个电话拨打
    onePhoneCall() {
        /*if (!this.platform.is('cordova')) {
            return false;
        }*/
        if (this.clientLData.mobileList.length > 0&&this.clientLData.mobileList.length<=1 && this.clientLData.mobileList[0].mobile) {
            //this.callPhoneNumber(this.clientLData.mobileList[0].mobile);
            this.callPhoneEvent(this.clientLData.mobileList[0].mobile);
            console.log('one');
        }
        if(this.clientLData.mobileList.length>1){
            //this.selectMobile.open();
            console.log('more');
            const phoneArray = [];
            this.clientLData.mobileList.forEach(phoneNumItem => {
                phoneArray.push({
                    text:phoneNumItem.mobile,
                    handler:() => {
                        //this.callPhoneNumber(phoneNumItem.mobile)
                        this.callPhoneEvent(phoneNumItem.mobile)
                    }
                });
            });
            this.adpActionSheetController.create({
                title:"选择电话",
                buttons:phoneArray
            }).present();
        }
    }

    // 跳转地图
    goMap() {
        let goMapMsg, latitude, longitude;
        if (!this.clientLData || !this.clientLData.addressList || !this.clientLData.addressList.length) {
            goMapMsg = '没有默认地址';
        } else {
            const defaultAddr = this.clientLData.addressList.filter(add => add.defaultIndicator == 1);

            if (defaultAddr.length) {
                if (defaultAddr[0].locationLatitude && defaultAddr[0].locationLongitude) {
                    latitude = defaultAddr[0].locationLatitude;
                    longitude = defaultAddr[0].locationLongitude;
                }
                goMapMsg = '';
                this.intoPage=false;
                this.navCtrl.push('ClientBMapPage', {
                    id: this.clientLData.leadId,
                    type: 1,           //1准客户,2核心客户
                    address:defaultAddr[0].address,
                    latitude:latitude,
                    longitude:longitude
                });
            } else {
                goMapMsg = '默认地址无法定位';
            }
            if (goMapMsg) {
                let toast = this.toastCtrl.create({
                    message: goMapMsg,
                    position: 'middle',
                    duration: 1200
                });
                toast.present();
            }
        }
    }


    /**
     * 拨打电话：创建跟进笔记、更新该客户活动跟踪状态
     *
     */

    callPhoneEvent(mobilePhone) {
        console.log(mobilePhone);
        this.callNumberService.makeCall(mobilePhone,
            this.callNumberService.initCustomerNoteLog(this.currentClientNum),
            true,
            {
                name: this.clientLData.name,
                customerId: this.currentClientNum,
                tel: mobilePhone
            }, () => {
                this.getProgressList(0);
                this.events.publish('refresh roster1', {
                    id: this.currentClientNum
                });
            });
    }


    /**
     *  返回
     */
    backToProPage() {
        this.intoPage=false;
        this.navCtrl.pop(null);
    }

    // 跳转至编辑
    goToEdit() {
        if (this.clientId == undefined)
            this.clientId = 1;
        this.intoPage=false;
        this.navCtrl.push('ClientsAddPage', {
            data: this.clientLData
        });
    }

    // 跳转至客户笔记
    goToNote(currentClientNum) {
        let base: BaseInfo = new BaseInfo();
        base.clientId = currentClientNum;
        base.clientName = this.clientLData.name;
        this.clientLData.mobileList[0]&&this.clientLData.mobileList[0].mobile?base.clientPhone = this.clientLData.mobileList[0].mobile:null;
        base.clientType = 1;
        this.intoPage=false;
        this.navCtrl.push('ClientNoteListPage', {
            clientNum: currentClientNum,
            base: base
        })
    }

    /**
     * 确认框
     *
     * @private
     * @param {any} msg 询问的消息
     * @param {any} okCallback 用户点击确定后的回调
     * @param {any} cancelCallback 用户点击取消后的回调
     * @memberof ScheduleAddPage
     */
    showConfirm(msg, okCallback, cancelCallback) {
        if (this.alertObj) return;
        this.alertObj = this.alertCtrl.create({
            enableBackdropDismiss: false,
            message: msg,
            buttons: [{
                text: this.curStrResource.StrCancel,
                handler: cancelCallback
            }, {
                text: this.curStrResource.StrOk,
                handler: okCallback
            }]
        });
        this.alertObj.onDidDismiss(() => this.alertObj = null);
        this.alertObj.present();
    }
}
